import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../pages/joy_product_detail_page.dart';
import 'LitplatformItem.dart';


class LitPlatformVoLWidget extends StatefulWidget {
  final List<PlatformVoList> platformList;
  final VoidCallback? onClose;
  final Function(PlatformVoList)? onPlatformSelected;
  final Function(PlatformVoList)? onPlatformCopySelected;

  const LitPlatformVoLWidget({
    Key? key,
    required this.platformList,
    this.onClose,
    this.onPlatformSelected,
    this.onPlatformCopySelected,
  }) : super(key: key);

  @override
  State<LitPlatformVoLWidget> createState() => _PlatformVoListWidgetState();
}

class _PlatformVoListWidgetState extends State<LitPlatformVoLWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFF1A1A1A),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16.r),
          topRight: Radius.circular(16.r),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题栏
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Select Shopping Platform'.tr,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                GestureDetector(
                  onTap: (){
                    // 关闭弹窗
                    Navigator.of(context).pop();
                    // 同时调用自定义的onClose回调
                    widget.onClose?.call();
                  },
                  child: Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Color(0xFF2A2A2A),
                      borderRadius: BorderRadius.circular(16.r),
                    ),
                    child: Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 18.w,
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 平台列表
          Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height * 0.7,
            ),
            child: LitilteredPlatformList(),
          ),
        ],
      ),
    );
  }

  Widget LitilteredPlatformList() {
    if (widget.platformList.isEmpty) {
      return _buildEmptyPlatformList();
    }

    // showFlag == 1）
    List<PlatformVoList> recommendedPlatforms = widget.platformList
        .where((platform) => (platform.showFlag ?? '0') == '1')
        .toList();

    // 优先查找litbuy平台，其次查找itao平台
    PlatformVoList? priorityPlatform;
    for (var platform in widget.platformList) {
      String platformName = (platform.name ?? "").toLowerCase();
      if (platformName.contains("litbuy")) {
        priorityPlatform = platform;
        debugPrint("🔍 找到优先平台 LitBuy: ${platform.name}");
        break;
      }
    }
    
    // 如果没有找到litbuy，则查找itao
    if (priorityPlatform == null) {
      for (var platform in widget.platformList) {
        String platformName = (platform.name ?? "").toLowerCase();
        if (platformName.contains("itao")) {
          priorityPlatform = platform;
          debugPrint("🔍 未找到LitBuy，使用iTao平台: ${platform.name}");
          break;
        }
      }
    }

    // 构建最终显示的平台列表
    List<PlatformVoList> finalPlatforms = [];
    
    // 添加推荐的平台
    finalPlatforms.addAll(recommendedPlatforms);

    if (priorityPlatform != null && !finalPlatforms.contains(priorityPlatform)) {
      finalPlatforms.add(priorityPlatform);
    }

    for (var platform in finalPlatforms) {
      print('🔍 [DEBUG] 最终平台: ${platform.name} - ${platform.productLink}');
    }

    if (finalPlatforms.isEmpty) {
      print('🔍 [DEBUG] 最终平台列表为空，显示空状态');
      return _buildEmptyPlatformList();
    }

    return ListView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.symmetric(vertical: 8.h),
      itemCount: finalPlatforms.length,
      itemBuilder: (context, index) {
        final platform = finalPlatforms[index];
        return LitPlatformItem(
          platformIcon: platform.logoImage,
          platformName: platform.nameEn ?? "",
          description: platform.platformDesc,
          copyLink: platform.productLink,
          recommendFlag: platform.recommendFlag ?? 0,
          showFlag: platform.showFlag ?? '0',
          recommendLogo: platform.recommendLogo,
          onTap: () {
            widget.onPlatformSelected?.call(platform);
          },
          onCopyLink: () {
            // 处理复制链接逻辑
            widget.onPlatformCopySelected?.call(platform);
          },
        );
      },
    );
  }

  // 构建空平台列表显示
  Widget _buildEmptyPlatformList() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.shopping_bag_outlined,
            color: Colors.grey[400],
            size: 60.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "No available shopping platforms at the moment",
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 16.sp,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            "Please try again later.",
            style: TextStyle(
              color: Colors.grey[500],
              fontSize: 14.sp,
            ),
          ),
        ],
      ),
    );
  }
}

